<?php
namespace app\common\model;

use think\facade\Db;

/**
 * 公众号模型
 */
class Wechat extends BaseModel
{
    // 定义表名
    protected $name = 'wechat';

    // 定义主键
    protected $pk = 'wechat_id';

    // 追加字段
    protected $append = [];

    /**
     * 是否授权
     */
    public function getStatusAttr($value)
    {
        $status = ['否','是'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 获取详情
     */
    public static function detail($applet_id = 0)
    {
        return self::where('applet_id',$applet_id)->find();
    }

    /**
     * 获取详情
     */
    public static function getWechat(array $filter = [])
    {
        return self::where($filter)->find();
    }

    /**
     * 清除历史数据
     */
    public function clear($applet_id)
    {
        $filter['applet_id'] = $applet_id;
        // 开启事务
        Db::startTrans();
        try {
            WechatBatchSend::where($filter)->delete();
            //获取图文记录
            if($text = Material::where($filter)->where('file_type',40)->select()){
                foreach ($text as $item) {
                    MaterialText::where('text_no',$item['text_no'])->delete();
                }
            }
            Material::where($filter)->delete();
            Keyword::where($filter)->delete();
            $this->where($filter)->delete();
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }

}
